package com.leetcode.sort;

import java.util.*;

/**
 * @author Dennis Li
 * @date 2020/7/24 22:15
 */
public class KthFrequent_347 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        Arrays.stream(nums).forEach(num -> map.put(num, map.getOrDefault(num, 0) + 1));
        // 按照第二列从小到大的顺序插入
        Queue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
        map.entrySet().forEach(queue::offer);
        int[] ans = new int[k];
        for (int i = 0; i < k; i++) {
            ans[i] = queue.poll().getKey();
        }
        return ans;
    }

}
